import time
import requests
from job import celery_job
from flask import request, json
from common.utils.myredis import myredis
from common.utils.common import get_ali_object
from common.utils.pay import AliPay
from second_flask.methods import db1


@celery_job.task()
def orders_check():
    score = int(time.time())

    print('111111111111111111111111111')
    list = myredis.zset_range_getall('order_no_list', score)
    print('list>>>>>>>>>>', list)
    for i in list:
        alipay = get_ali_object()
        query_params = alipay.query_pay(
            out_trade_no=i.decode()
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        res = requests.get(pay_url).text
        # print('res>>>>',res)
        aa = json.loads(res)
        out_trade_no = aa['alipay_trade_query_response']['out_trade_no']
        trade_no = aa['alipay_trade_query_response']['trade_no']
        print(out_trade_no)
        print(trade_no)
        status = aa["alipay_trade_query_response"]['code']
        print('status>>>>>>>>>', status)
        if status == '10000':
            requests.get("http://127.0.0.1:5000/callback?trade_no='%s'&&out_trade_no='%s'" % (trade_no, out_trade_no))
        else:
            sql = "update orders set status=%d where order_no='%s'" % (4, i.decode)
            db1.update(sql)
            db1.commit()
        return 'ok'
